import storys from '@/models/storys';
import schedule from '@/models/schedule';
import storyLock from '@/models/storyLock';
import { ObjectId } from 'mongodb';
import dayjs from 'dayjs';
import { addLogs } from '../logs';

const loop = async (index, arr, callback) => {
  let i = index;
  if (i >= arr.length) return true;
  const item = arr[i];
  await callback(item);
  i += 1;
  loop(i, arr, callback);
  return true;
};

// 循环developerList
const loopDeveloperList = async (developerList, storyId) => {
  try {
    const res = await loop(0, developerList, async (item) => {
      const data = {
        developerName: item.developerName,
        developerId: item.developerId,
        taskList: item.taskList,
        storyId: new ObjectId(storyId),
      };
      await schedule.updateAdd(data, { _id: new ObjectId(item._id) });
    });
    return res;
  } catch (err: any) {
    console.log(err);
    throw new Error(err.message);
  }
};

// 解锁
export const handleCloseLock = async (params) => {
  const { storyId, personName, personId } = params;
  const info = await storys.findOne({ _id: new ObjectId(storyId) });
  await storyLock.updateAdd({ storyId, isLock: false, updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss') }, { storyId });
  addLogs(1, 15, personName, [info?.name || ''], personId);
  return true;
};

// 对象数组去重
const handleData = (arr) => {
  const temp: any = [];
  const ids: any = [];
  for (let i = 0; i < arr.length; i += 1) {
    const item: any = arr[i];
    if (ids.indexOf(item._id) === -1) {
      ids.push(item._id);
      temp.push(item);
    }
  }
  return temp;
};

// 获取现在这个需求已经关联的开发人员。如果有，和入参取并集，以入参为主
const getExitPersonList = async (developerList) => {
  const res = await schedule.getList();
  if (res && Array.isArray(res) && res.length) {
    // 把入参放在前边，这样的话遍历的时候不存在旧数据覆盖新数据
    const result = handleData([...developerList, ...res]);
    return result;
  }
  return developerList;
};

// 生成排期计划
export const hanleSchedule = async (params) => {
  const { storyId, developOwner, developEnv, developerList, timeNodes, personName, personId, testArea } = params;
  try {
    const info = await storys.findOne({ _id: new ObjectId(storyId) });
    // 更新需求详情表里的值
    await storys.update({ developOwner, developEnv, timeNodes, testArea }, { _id: new ObjectId(storyId) });
    // 获取现在已经存在的。和入参进行对比。取并集
    // const result = await getExitPersonList(developerList);
    // 删除当前需求关联的人员任务
    await schedule.deleteMany({
      storyId: new ObjectId(storyId),
    });
    // 循环developerList，往排期计划表里插入数据，如果有就覆盖
    await loopDeveloperList(developerList, storyId);
    // 把锁清掉
    await handleCloseLock({ storyId });
    // 返给前端true。让前端把锁的状态变成未锁。别人可以继续编辑
    // 生成排期计划加日志
    addLogs(1, 14, personName, [info?.name || ''], personId);
    return true;
  } catch (err: any) {
    console.log(err);
    throw new Error(err.message);
  }
};

// 加锁
export const hanleOnLock = async (params) => {
  try {
    const { isLock, storyId, personName, personId } = params;
    const info = await storys.findOne({ _id: new ObjectId(storyId) });
    // 加锁表
    const res = await storyLock.updateAdd({ storyId, isLock, personName, personId, updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss') }, { storyId });
    // 加日志
    addLogs(1, 13, personName, [info?.name || ''], personId);
    return res;
  } catch (err: any) {
    throw new Error(err.message);
  }
};

// 锁状态
export const getLockStatus = async (params) => {
  try {
    const { storyId, personId, personName } = params;
    const res = await storyLock.findOne({ storyId });
    if (res && res.isLock && res.personId === personId) {
      await hanleOnLock({ storyId, isLock: true, personId, personName });
      return false;
    }
    if (res && res.isLock) {
      return true;
    }
    return true;
  } catch (err: any) {
    throw new Error(err.message);
  }
};

// 是否有加锁
export const handleLockInfo = async (params) => {
  try {
    const { storyId, personId, personName } = params;
    const res = await storyLock.findOne({ storyId });
    // if (res && res.personId === personId) {
    //   await hanleOnLock({ storyId, isLock: true, personId, personName });
    //   return null;
    // }
    // 如果已经加锁，返回加锁信息
    if (res && res.isLock) {
      return res;
    }
    // 如果没有加锁，那么加锁，返回信息为空，前端判断为空的话表示加锁成功
    await hanleOnLock({ ...params, isLock: true });
    return null;
    // 查一下是否加锁
  } catch (err: any) {
    throw new Error(err.message);
  }
};

// 获取需求的排期计划
export const hanleGetSchedule = async (params) => {
  try {
    const { storyId } = params;
    // 联表查询。需求表和排期表
    const res = await storys.unionStorySchedule({ _id: new ObjectId(storyId) });
    // 处理空数据
    if (res && res.length) {
      const info = res[0];
      if (!info.developOwner) info.developOwner = null;
      if (!info.developEnv) info.developEnv = null;
      if (!info.testArea) info.testArea = null;
      if (!info.timeNodes) info.timeNodes = null;
      return info;
    }
    return {};
  } catch (err: any) {
    console.log(err);
    throw new Error(err.message);
  }
};
